package net.expectx.common.single.third.ali;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.base.BaseResultConstants;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;


/**
 * @author lijian
 * 阿里支付
 */
public class AliPayUtil {
    private static final Logger LOGGER = Logger.getLogger(AliPayUtil.class);

    private static String ALI_PAY_APP_ID;
    private static String  ALI_PAY_MERCHANT_PRIVATE_KEY;
    private static String ALI_PAY_PUBLIC_KEY;
    private static String  ALI_PAY_GATEWAY_URL ;
    private static String  ALI_PAY_SIGN_TYPE ;
    private static AliPayUtil aliPayUtil;
    private AliPayUtil(){}
    public static synchronized  AliPayUtil getInstance(){
        if (aliPayUtil==null){
            aliPayUtil=new AliPayUtil();
        }
        return aliPayUtil;
    }

    public  void init(String appId,String merchantPrivateKey,String publicKey,String signType,String gatewayUrl ) {
        ALI_PAY_APP_ID=appId;
        ALI_PAY_GATEWAY_URL=gatewayUrl;
        ALI_PAY_MERCHANT_PRIVATE_KEY = merchantPrivateKey;
        ALI_PAY_PUBLIC_KEY=publicKey;
        ALI_PAY_SIGN_TYPE=signType;
    }

    /**
     * 发起Page支付
     * @param orderId
     * @param totalAmount
     * @param orderName
     * @param orderDesc
     * @param aliPayReturnUrl
     * @param aliPayNotifyUrl
     * @return
     */
    public  BaseResult doPagePay(String orderId, Double totalAmount, String orderName, String orderDesc, String aliPayReturnUrl, String aliPayNotifyUrl){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(ALI_PAY_GATEWAY_URL, ALI_PAY_APP_ID, ALI_PAY_MERCHANT_PRIVATE_KEY, "json", "utf-8", ALI_PAY_PUBLIC_KEY, ALI_PAY_SIGN_TYPE);
            /**
             * 设置请求参数
             */
            AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
            aliPayRequest.setReturnUrl(aliPayReturnUrl);
            aliPayRequest.setNotifyUrl(aliPayNotifyUrl);
            Map bizContent = new HashMap(7);
            /*订单号*/
            bizContent.put("out_trade_no", orderId);
            /*支付金额*/
            bizContent.put("total_amount", totalAmount);
            /*订单名称*/
            bizContent.put("subject", orderName);
            /*商品描述*/
            bizContent.put("body", orderDesc);
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            aliPayRequest.setBizContent(JSON.toJSONString(bizContent));
            String result = alipayClient.pageExecute(aliPayRequest).getBody();
            return  new BaseResult(true,null,result);
        }catch (AlipayApiException e){
            return  new BaseResult(false,e.getErrMsg(),null);
        }
    }

    /**
     * 发起手机网站支付
     * @param orderId
     * @param totalAmount
     * @param orderName
     * @param orderDesc
     * @param aliPayReturnUrl
     * @param aliPayNotifyUrl
     * @return
     */
    public  BaseResult doWapPay(String orderId, Double totalAmount, String orderName, String orderDesc, String aliPayReturnUrl, String aliPayNotifyUrl){
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(ALI_PAY_GATEWAY_URL, ALI_PAY_APP_ID, ALI_PAY_MERCHANT_PRIVATE_KEY, "json", "utf-8", ALI_PAY_PUBLIC_KEY, ALI_PAY_SIGN_TYPE);
            AlipayTradeWapPayRequest aliPayRequest = new AlipayTradeWapPayRequest();
            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(orderId);
            model.setSubject(orderName);
            model.setTotalAmount(String.valueOf(totalAmount));
            model.setBody(orderDesc);
            model.setTimeoutExpress("2m");
            model.setProductCode("QUICK_WAP_WAY");
            aliPayRequest.setBizModel(model);
            // 设置同步地址
            aliPayRequest.setReturnUrl(aliPayReturnUrl);
            // 设置异步通知地址
            aliPayRequest.setNotifyUrl(aliPayNotifyUrl);
            String form = alipayClient.pageExecute(aliPayRequest).getBody();

            return  new BaseResult(true,null,form);
        }catch (AlipayApiException e){
            return  new BaseResult(false,e.getErrMsg(),null);
        }
    }

    /**
     * 订单查询
     * @param tradeNo
     * @return
     */
    public BaseResult doQuery(String tradeNo) {
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_PAY_GATEWAY_URL, ALI_PAY_APP_ID, ALI_PAY_MERCHANT_PRIVATE_KEY, "json", "utf-8", ALI_PAY_PUBLIC_KEY, ALI_PAY_SIGN_TYPE);

        AlipayTradeQueryRequest aLiPayRequest = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setTradeNo(tradeNo);
        aLiPayRequest.setBizModel(model);

        try {
            AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(aLiPayRequest);
            JSONObject json=JSONObject.parseObject(alipayTradeQueryResponse.getBody());
            LOGGER.info(json);
            if (json.getJSONObject("alipay_trade_query_response").getInteger("code")==10000){
                return new BaseResult(Boolean.TRUE, BaseResultConstants.SUCCESS, json.getJSONObject("alipay_trade_query_response"));
            }else{
                return new BaseResult(Boolean.FALSE, json.getJSONObject("alipay_trade_query_response").getInteger("code"), json.getJSONObject("alipay_trade_refund_response").getString("sub_msg"), null);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return new BaseResult(Boolean.FALSE, BaseConstants.FAILE, "系统错误:" + e.getErrMsg(), null);

        }
    }

    /**
     * 申请退款
     * @param tradeNo
     * @param refundAmount
     * @param refundReason
     * @return
     */
    public BaseResult doRefund(String tradeNo, Double refundAmount,String refundReason ) {
        AlipayClient alipayClient = new DefaultAlipayClient(ALI_PAY_GATEWAY_URL, ALI_PAY_APP_ID, ALI_PAY_MERCHANT_PRIVATE_KEY, "json", "utf-8", ALI_PAY_PUBLIC_KEY, ALI_PAY_SIGN_TYPE);
        AlipayTradeRefundRequest aLiPayRequest = new AlipayTradeRefundRequest();

        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setTradeNo(tradeNo);
        model.setRefundAmount(String.valueOf(refundAmount));
        model.setRefundReason(refundReason);
        aLiPayRequest.setBizModel(model);

        try {
            AlipayTradeRefundResponse alipayTradeRefundResponse = alipayClient.execute(aLiPayRequest);
            JSONObject json=JSONObject.parseObject(alipayTradeRefundResponse.getBody());
            LOGGER.info(json);
            if (json.getJSONObject("alipay_trade_refund_response").getInteger("code")==10000){
                return new BaseResult(Boolean.TRUE, BaseResultConstants.SUCCESS, json.getJSONObject("alipay_trade_refund_response"));
            }else{
                return new BaseResult(Boolean.FALSE, json.getJSONObject("alipay_trade_refund_response").getInteger("code"), json.getJSONObject("alipay_trade_refund_response").getString("sub_msg"), null);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return new BaseResult(Boolean.FALSE, BaseConstants.FAILE, "系统错误:" + e.getErrMsg(), null);

        }
    }
}
